var jwt = require('jsonwebtoken')
// var jwt = require('koa-jwt')
var {secret} = require('../config')
module.exports = {
    // 生成token
    async generateToken(_id, mobile_code) {
        const token = await jwt.sign({
            _id,
            mobile_code
        }, secret, { expiresIn: 1000 * 60 * 60 * 24 })
        return token
    },

    // token认证中间件
   async auth(ctx,next) {
        const {authorization=''}=ctx.request.header
        const token = authorization.replace('Bearer ', '')
        try{
            const user=jwt.verify(token,secret)
            ctx.state.user=user
        }catch (e) {
            ctx.throw(401,e.message)
        }
        await next()
    },

    // 授权处理中间件
    async checkOwner(ctx, next) {
      // 已经登录就有ctx.state.user字段
      if (ctx.params.id !== ctx.state.user._id) {
          ctx.throw(403, '没有权限', ctx.state.user)
      } else {
          await next()
      }
  }
}